﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Win = System.Drawing;
using System.Runtime.CompilerServices;

namespace Jage.Common
{
    static public class BitmapExtension
    {

        static public Rectangle GetNonTransparentRectangle(this Win.Bitmap bitmap)
        {
            if (bitmap.Width > 0 && bitmap.Height > 0)
            {
                var left = GetBoundX(bitmap, 0, 1, bitmap.Width - 1);
                if (left < bitmap.Width - 1)
                {
                    var right = GetBoundX(bitmap, bitmap.Width - 1, -1, left + 1);
                    if (left < right)
                    {
                        var top = GetBoundY(bitmap, 0, 1, bitmap.Height - 1, left + 1, right - 1);
                        if (top < bitmap.Height - 1)
                        {
                            var bottom = GetBoundY(bitmap, bitmap.Height - 1, -1, top + 1, left + 1, right - 1);

                            return new Rectangle(left, top, right - left, bottom - top);
                        }
                    }
                }
            }
            return Rectangle.Empty;
        }

        static private int GetBoundX(Win.Bitmap bitmap, int startX, int stepX, int endX)
        {
            var x = startX;
            while (x != endX && ColumnIsTransparent(bitmap, x))
            {
                x += stepX;
            }
            return x;
        }

        static private bool ColumnIsTransparent(Win.Bitmap bitmap, int x)
        {
            var height = bitmap.Size.Height;
            for (var y = 0; y < height; y++)
            {
                if (bitmap.GetPixel(x, y).A != 0)
                {
                    return false;
                }
            }
            return true;
        }

        static private int GetBoundY(Win.Bitmap bitmap, int startY, int stepY, int endY, int leftBound, int rightBound)
        {
            var y = startY;
            while (y != endY && RowIsTransparent(bitmap, y, leftBound, rightBound))
            {
                y += stepY;
            }
            return y;
        }

        static private bool RowIsTransparent(Win.Bitmap bitmap, int y, int leftBound, int rightBound)
        {
            var width = bitmap.Size.Width;
            for (var x = leftBound; x <= rightBound; x++)
            {
                if (bitmap.GetPixel(x, y).A != 0)
                {
                    return false;
                }
            }
            return true;
        }

    }
}
